package com.ruoyi.business.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.business.domain.DailyTrain;
import com.ruoyi.business.domain.dto.DailyTrainStationGroupDTO;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.DailyTrainStation;
import com.ruoyi.business.service.IDailyTrainStationService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.business.mapper.DailyTrainMapper;

/**
 * 每日车站Controller
 * 
 * @author ruoyi
 * @date 2025-03-06
 */
@RestController
@RequestMapping("/business/daily-train-station")
public class DailyTrainStationController extends BaseController
{
    @Autowired
    private IDailyTrainStationService dailyTrainStationService;

    @Autowired
    private DailyTrainMapper dailyTrainMapper;

    /**
     * 查询每日车站列表
     */
    @PreAuthorize("@ss.hasPermi('business:daily-train-station:list')")
    @GetMapping("/list")
    public TableDataInfo list(DailyTrainStation dailyTrainStation)
    {
        startPage();
        List<DailyTrainStation> list = dailyTrainStationService.selectDailyTrainStationList(dailyTrainStation);
        return getDataTable(list);
    }

    /**
     * 导出每日车站列表
     */
    @PreAuthorize("@ss.hasPermi('business:daily-train-station:export')")
    @Log(title = "每日车站", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DailyTrainStation dailyTrainStation)
    {
        List<DailyTrainStation> list = dailyTrainStationService.selectDailyTrainStationList(dailyTrainStation);
        ExcelUtil<DailyTrainStation> util = new ExcelUtil<DailyTrainStation>(DailyTrainStation.class);
        util.exportExcel(response, list, "每日车站数据");
    }

    /**
     * 获取每日车站详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:daily-train-station:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(dailyTrainStationService.selectDailyTrainStationById(id));
    }

    /**
     * 新增每日车站
     */
    @PreAuthorize("@ss.hasPermi('business:daily-train-station:add')")
    @Log(title = "每日车站", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DailyTrainStation dailyTrainStation)
    {
        dailyTrainStation.setId(IdUtil.getSnowflakeNextId());
        return toAjax(dailyTrainStationService.insertDailyTrainStation(dailyTrainStation));
    }

    /**
     * 修改每日车站
     */
    @PreAuthorize("@ss.hasPermi('business:daily-train-station:edit')")
    @Log(title = "每日车站", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DailyTrainStation dailyTrainStation)
    {
        return toAjax(dailyTrainStationService.updateDailyTrainStation(dailyTrainStation));
    }

    /**
     * 删除每日车站
     */
    @PreAuthorize("@ss.hasPermi('business:daily-train-station:remove')")
    @Log(title = "每日车站", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(dailyTrainStationService.deleteDailyTrainStationByIds(ids));
    }

    /**
     * 按车次分组查询每日车站列表
     */
    @PreAuthorize("@ss.hasPermi('business:daily-train-station:list')")
    @GetMapping("/listByGroup")
    public TableDataInfo listByGroup(DailyTrainStation dailyTrainStation) {
        // 获取分页信息
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        
        // 1. 首先获取不同的车次编号列表(分页)
        List<String> trainCodes = dailyTrainStationService.selectDistinctTrainCodes(dailyTrainStation, pageNum, pageSize);
        
        // 2. 获取车次总数
        int total = dailyTrainStationService.countDistinctTrainCodes(dailyTrainStation);
        
        // 3. 然后根据分页后的车次编号查询完整的车站数据
        List<DailyTrainStationGroupDTO> groups = new ArrayList<>();
        if (!trainCodes.isEmpty()) {
            // 设置车次编号列表条件
            dailyTrainStation.setTrainCodes(trainCodes);
            
            // 查询这些车次的所有车站数据(不分页)
            List<DailyTrainStation> stations = dailyTrainStationService.selectDailyTrainStationByTrainCodes(dailyTrainStation);
            
            // 按trainCode分组
            Map<String, List<DailyTrainStation>> stationGroups = stations.stream()
                    .collect(Collectors.groupingBy(DailyTrainStation::getTrainCode));
            
            // 转换为DTO对象
            for (String trainCode : trainCodes) {
                List<DailyTrainStation> trainStations = stationGroups.getOrDefault(trainCode, new ArrayList<>());
                
                if (!trainStations.isEmpty()) {
                    DailyTrainStationGroupDTO groupDTO = new DailyTrainStationGroupDTO();
                    groupDTO.setTrainCode(trainCode);
                    groupDTO.setStations(trainStations);
                    
                    // 获取车次类型(使用现有业务逻辑)
                    DailyTrainStation firstStation = trainStations.get(0);
                    DailyTrain train = new DailyTrain();
                    train.setDate(firstStation.getDate());
                    train.setCode(trainCode);
                    List<DailyTrain> trains = dailyTrainMapper.selectDailyTrainList(train);
                    if (!trains.isEmpty()) {
                        groupDTO.setTrainType(trains.get(0).getType());
                    } else {
                        // 如果找不到车次，默认设置为其他类型
                        String defaultType = trainCode.startsWith("G") ? "G" :
                                trainCode.startsWith("D") ? "D" : "OTHER";
                        groupDTO.setTrainType(defaultType);
                    }
                    
                    groups.add(groupDTO);
                }
            }
        }
        
        // 4. 返回分页结果
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(groups);
        rspData.setTotal(total);
        rspData.setMsg("查询成功");
        
        return rspData;
    }
}
